package com.zheng.oa.admin.controller.hr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.zheng.common.base.BaseController;
import com.zheng.common.util.CamelUnderlineConverter;
import com.zheng.hr.dao.model.HrTrain;
import com.zheng.hr.dao.model.HrTrainUser;
import com.zheng.hr.rpc.api.HrTrainService;
import com.zheng.hr.rpc.api.HrTrainUserService;
import com.zheng.oa.common.constant.OaResult;
import com.zheng.oa.common.constant.OaResultConstant;
import com.zheng.upms.dao.model.UpmsUser;
import com.zheng.upms.rpc.api.UpmsApiService;
import com.zheng.upms.rpc.api.UpmsUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xinqi
 * Date: 2017/11/16
 * Time: 11:17
 */
@Controller
@Api(value = "培训管理", description = "培训管理")
@RequestMapping("/oa/hr/train")
public class HrTrainController extends BaseController {
    @Autowired
    private HrTrainService trainService;
    @Autowired
    private HrTrainUserService trainUserService;
    @Autowired
    private UpmsUserService upmsUserService;
    @Autowired
    private UpmsApiService apiService;

    @ApiOperation(value = "培训管理首页")
    @RequiresPermissions("oa:hr:train:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(Model model) {
        return "/manage/hr/train/index.jsp";
    }

    @ApiOperation(value = "培训列表")
    @RequiresPermissions("oa:hr:train:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(@RequestParam(required = false, defaultValue = "1", value = "pageNumber") int pageNumber,
                       @RequestParam(required = false, defaultValue = "10", value = "pageSize") int pageSize,
                       @RequestParam(required = false, value = "sortName") String sortName,
                       @RequestParam(required = false, value = "sortOrder") String sortOrder,
                       @RequestParam(required = false, value = "beginDate") String beginDate,
                       @RequestParam(required = false, value = "endDate") String endDate) {
        Wrapper<HrTrain> wrapper = new EntityWrapper<>();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            if (sortOrder.equalsIgnoreCase("asc")) {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), true);
            } else {
                wrapper = wrapper.orderBy(CamelUnderlineConverter.camel2underline(sortName), false);
            }
        }
        if (StringUtils.isNotBlank(beginDate) && StringUtils.isNotBlank(endDate)) {
            wrapper.where("begin_time  between'" + beginDate + "'and'" + endDate + "'");
        }
        wrapper.where("status!=" + HrTrain.DELETE);
        wrapper.orderBy("begin_time");
        wrapper = apiService.dataScopeFilter(wrapper, getUsername());
        Page<Map<String, Object>> page = trainService.selectMapsPage(new Page<>(pageNumber, pageSize), wrapper);
        List<Map<String, Object>> maps = page.getRecords();
        for (Map<String, Object> train : maps) {
            String state = "正常";
            int status = Integer.parseInt(train.get("status").toString());
            if (status == HrTrain.CANCEL) {
                state = "已取消";
            } else if (status == HrTrain.FINISH) {
                state = "已结束";
            }
            train.put("state", state);
        }
        int total = trainService.selectCount(wrapper);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", maps);
        result.put("total", total);
        return result;
    }

    @ApiOperation(value = "新增培训")
    @RequiresPermissions("oa:hr:train:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        return "/manage/hr/train/create.jsp";
    }

    @ApiOperation(value = "新增培训")
    @RequiresPermissions("oa:hr:train:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody HrTrain train) {
        try {
            trainService.insertTrain(train, getUsername());
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "修改培训")
    @RequiresPermissions("oa:hr:train:update")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public String update(Integer id, Model model) {
        HrTrain train = trainService.selectById(id);
        EntityWrapper<HrTrainUser> trainUserEntityWrapper = new EntityWrapper<>();
        trainUserEntityWrapper.where("train_id=" + train.getId());
        List<HrTrainUser> trainUsers = trainUserService.selectList(trainUserEntityWrapper);
        model.addAttribute("trainUsers", JSONObject.toJSON(trainUsers));
        String trainInstructorName = "";
        if (train.getTrainInstructorId() != null) {
            UpmsUser upmsUser = upmsUserService.selectById(train.getTrainInstructorId());
            trainInstructorName = upmsUser.getRealname();
        }
        model.addAttribute("trainInstructorName", trainInstructorName);
        model.addAttribute("train", train);
        return "/manage/hr/train/update.jsp";
    }

    @ApiOperation(value = "修改培训")
    @RequiresPermissions("oa:hr:train:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@RequestBody HrTrain train) {
        try {
            trainService.updateTrain(train);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "删除培训")
    @RequiresPermissions("oa:hr:train:delete")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        try {
            trainService.updateTrainStatus(ids,HrTrain.DELETE);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "取消培训")
    @RequiresPermissions("oa:hr:train:delete")
    @RequestMapping(value = "/cancelTrain/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object cancel(@PathVariable("ids") String ids) {
        try {
            trainService.updateTrainStatus(ids,HrTrain.CANCEL);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }
    @ApiOperation(value = "恢复培训")
    @RequiresPermissions("oa:hr:train:update")
    @RequestMapping(value = "/recoveryTrain/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object recovery(@PathVariable("ids") String ids) {
        try {
            trainService.updateTrainStatus(ids,HrTrain.NORMAL);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @RequiresPermissions("oa:hr:train:update")
    @RequestMapping(value = "/updateTrainUsers", method = RequestMethod.GET)
    public String updateTrainUsers(Integer id, Model model) {
        List<Map<String, Object>> trainUsers = trainUserService.selectTrainUsers(id);
        model.addAttribute("trainUsers", JSON.toJSON(trainUsers));
        return "/manage/hr/train/updateTrainUsers.jsp";
    }

    @RequiresPermissions("oa:hr:train:update")
    @RequestMapping(value = "/updateTrainUsers", method = RequestMethod.POST)
    @ResponseBody
    public Object updateTrainUsers(@RequestBody JSONArray trainUserList) {
        List<HrTrainUser> trainUsers = trainUserList.toJavaList(HrTrainUser.class);
        try {
            trainUserService.updateTrainUsers(trainUsers);
        } catch (Exception e) {
            return new OaResult(OaResultConstant.FAILED, e.getMessage());
        }
        return new OaResult(OaResultConstant.SUCCESS, null);
    }

    @ApiOperation(value = "修改培训详情")
    @RequiresPermissions("oa:hr:train:update")
    @RequestMapping(value = "/updateSummary", method = RequestMethod.GET)
    public String updateSummary(Integer id, Model model) {
        HrTrain train = trainService.selectById(id);
        model.addAttribute("train", train);
        return "/manage/hr/train/updateSummary.jsp";
    }
}
